import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:sample2/utils/json_util.dart';
import 'package:sample2/utils/local_storage.dart';
import 'package:sample2/utils/string_util.dart';

class UserInfo extends Object {
  String? name;
  String? age;
  String? username;
  String? token;
  String? department;
  String? userid;
  String? avatar;
  String? nickname = "--";

  UserInfo({this.name, this.age, this.username, this.department});

  static Future<UserInfo> fromCache() async {
    LocalStorage shared = await LocalStorage.getShared();
    String? jsonStr = shared.getPrefs().getString("userInfo");
    Map? cachedObj = JsonUtil.jsonObjectFromString(jsonStr);
    UserInfo userInfo = UserInfo.fromObject(cachedObj);
    return userInfo;
  }

  UserInfo.fromObject(Map? responseContent) {
    name = responseContent?["name"];
    age = responseContent?["age"]?.toString();
    username = responseContent?["username"];
    userid = responseContent?["userid"];
    token = responseContent?["token"];
    nickname = responseContent?["nickname"];
    avatar = responseContent?["avatar"];
  }

  bool hasLogin() {
    return !StringUtil.isNullOrEmpty(token);
  }

  saveToCache() {
    shared?.getPrefs().setString("userInfo", toString()).then((value) {
      debugPrint("save user info :${value.toString()} success");
    });
  }

  removeFromCache() {
    shared?.getPrefs().remove("userInfo").then((value) {
      debugPrint("remove user info success");
    });
  }

  @override
  String toString() {
    return JsonUtil.jsonStringFromJsonMap(HashMap.from({
      "name": name,
      "age": age,
      "username": username,
      "token": token,
      "department": department,
      "userid": userid
    }));
  }
}
